package com.cjl.host.interceptor;

import com.cjl.host.pojos.Host;
import com.cjl.utils.thread.HostThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author cjl
 * @version v1.0
 * @description TODO
 * @createTime 2023/2/16 11:49
 */
@Slf4j
@Component
public class HostFirstInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        try {
            //从请求头中获取id
            String hostId = request.getHeader("hostId");
            if (hostId == null) return false;
            Host host = Host.builder()
                    .id(Integer.parseInt(hostId))
                    .build();
            //将id封装到threadLocal中
            HostThreadUtil.set(host);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return false;
        }
        log.info("添加hostId到HostThreadUtil中。。。");
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HostThreadUtil.remove();

    }
}
